home *** CD-ROM | disk | FTP | other *** search
- Path: colossus.holonet.net!russell
- From: russell@news.mdli.com (Russell Blackadar)
- Newsgroups: comp.lang.c++
- Subject: Re: Virtual Members: Difficult Question
- Date: 20 Jan 1996 00:11:14 GMT
- Organization: HoloNet National Internet Access System: 510-704-1058/modem
- Message-ID: <4dpbv2$l6k@colossus.holonet.net>
- References: <4dmha6$80c@marlin.ssnet.com>
- NNTP-Posting-Host: jubal.mdli.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Ray Helie (helie@ssnet.com) wrote:
- [...]
- : In the microsoft foundation class library, there is a CObject class. I
- : create an inherited class that is a virtual class as follows:
- ^^^^^^^ actually, "abstract"
- [...]
- : class C_BASE : public CObject
- [...]
- : class C_ITEM : public C_BASE
- [...]
- : void func1 (CObject* pItem)
- : {
- : C_BASE* base;
- : base = pItem;
- ???????????? ILLEGAL
- You should get a compile error on this stmt. No automatic
- conversion exists from a base pointer to a derived pointer.
-
- : pItem-> index ();
- : // (i) is the above call to index () allowed? or did i lose virtual
- : // information about the class C_BASE when I went to the CObject
- : // pointer?
-
- It should be illegal, with a compile error. CObject has no
- index member. It *would* be legal to have base->index(),
- assuming you did the cast right on the previous statement.
- Not terribly safe, but legal.
-
-
- : On to the difficult part:
- [...]
- : I'm reading and writing object states to disk...
-
- Oh boy, I smell trouble. Are you expecting to use objects
- saved from a previous run, for example? The vtbl pointers
- (and any other pointers) will be all wrong. This is the
- classic problem of "persistent objects" which requires a
- very careful solution.
-
- : main ()
- : {
- : C_ITEM item;
- : writeObject ((CObject*)&item,sizeof(C_ITEM));
- : readObject ((CObject*)&item,sizeof(C_ITEM));
- : }
-
-
- : void readObject (CObject* pObject,int pSize)
- : {
- : C_BASE* base = pObject;
- ^^^^^^^^^^ ??? NEEDS CAST, SEE ABOVE
- : base-> index (); // this call works fine
- : Read ((char*)&pObject,pSize);
-
- A few things are very wrong here. The "&" is surely wrong, as
- Read apparently is going to store pSize bytes at the location of
- this pointer, but its size is just sizeof(CObject*), i.e. 2 or
- 4 bytes.
-
- If you remove the "&", it has at least a chance of working, but
- the C++ standard gives you no guarantee that (CObject*)&item
- has the same numerical value as &item. I think that it actually
- will not in some popular C++ implementations (owing to the vtbl),
- but maybe you are OK in VC++.
-
- More important, perhaps, are the caution flags I raised earlier.
- It just is not a good idea to treat an object like a bucket of
- bits, as your (char*) cast implies you're about to do.
-
- Good luck.
- --
- Russell Blackadar russell@mdli.com
-